package com.nebula.api.common.exception;

import link.ahsj.core.entitys.ApiModel;
import link.ahsj.core.entitys.CodeMsg;
import link.ahsj.core.exception.ErrorCode;
import lombok.extern.log4j.Log4j2;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.util.CollectionUtils;
import org.springframework.validation.ObjectError;
import org.springframework.web.HttpRequestMethodNotSupportedException;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.ArrayList;
import java.util.List;

/**
 * @author Eastern unbeaten
 * @email chenshiyun2011@163.com
 * @date 2019-08-15 18:16
 */
@Log4j2
@RestControllerAdvice
public class ExceptionAdvice {

    /**
     * 异常处理器
     * TODO  这里的错误消息应该封装到 message 而不是data
     *
     * @param
     * @return
     */
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public ResponseEntity<ApiModel> methodArgumentNotValidExceptionAdvice(MethodArgumentNotValidException e) {
        List<ObjectError> errors = e.getBindingResult().getAllErrors();
        List<String> messages = new ArrayList<>(errors.size());
        if (!CollectionUtils.isEmpty(errors)) {
            errors.forEach(item -> messages.add(item.getDefaultMessage()));
        }
        return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(ApiModel.error(ErrorCode.UNVALID, CodeMsg.VALID_ERR_MSG, messages));
    }

    @ExceptionHandler(HttpRequestMethodNotSupportedException.class)
    public ResponseEntity<ApiModel> httpRequestMethodNotSupportedExceptionAdvice(HttpRequestMethodNotSupportedException e) {
        log.error(e);
        return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(ApiModel.error("请求方式不正确"));
    }


}
